﻿namespace TestResults
{
    using System;
    using System.Windows.Forms;

    using TfsReportRenderer;

    public partial class Form1 : Form
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Form1"/> class.
        /// </summary>
        public Form1()
        {
            this.InitializeComponent();
            
            // don't crash and burn when you cant access user data
            try
            {
                this.textBox1.Text = Properties.Settings.Default.lastTfsUri;
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
            }
        }

        private void BtnConnectClick(object sender, EventArgs e)
        {
            var tfsUri = this.textBox1.Text;
            
            // try to save last url as a convienience, don't crash if not possible
            try
            {
                if (Properties.Settings.Default.lastTfsUri != tfsUri)
                {
                    Properties.Settings.Default.lastTfsUri = tfsUri;
                    Properties.Settings.Default.Save();
                }
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
            }

            var tfsContext = new TfsContext(new Uri(tfsUri));
            this.cbTeamProjects.DataSource = tfsContext.TeamProjects;
        }

        public void ButtonBuildReportClick(object sender, EventArgs e)
        {
            if (this.cbTeamProjects.Items.Count > 0)
            {
                var teamProject = this.cbTeamProjects.SelectedValue.ToString();
                var selectedTestPlan = this.cbTestPlans.SelectedValue.ToString();
                try
                {
                    var tfsContext = new TfsContext(new Uri(this.textBox1.Text));
                    this.ITestSuiteBindingSource.DataSource = tfsContext.GetReportData(teamProject, selectedTestPlan, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

                this.reportViewer1.RefreshReport();
            }
            else
            {
                MessageBox.Show(@"Please connect to TFS first");
            }
        }

        private void CbTeamProjectsSelectedIndexChanged(object sender, EventArgs e)
        {
            var teamProject = ((ComboBox)sender).SelectedItem.ToString();

            if (!string.IsNullOrEmpty(teamProject))
            {
                var tfsContext = new TfsContext(new Uri(this.textBox1.Text));
                this.cbTestPlans.DataSource = tfsContext.GetTestPlans(teamProject);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
